import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '../layout/Index.vue'
import Dash from '../views/Dashboard'
import local from '@/utils/local.js'
// 引入需要动态计算的路由
import SyncRouter from './SyncRouter'

Vue.use(VueRouter)

// 解决重复点击面包屑导航报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Index,
    // 重定向
    redirect: '/dashboard',
    children: [
      // 后台首页
      {
        path: '/dashboard',
        meta: { name: '后台首页', icon: 'icon-shouye' },
        component: Dash
      }
    ]
  },
  {
    path: '/login',
    component: () =>
      import(/* webpackChunkName: "login" */ '../views/Login.vue')
  },
  {
    path: '*',
    redirect: '/404'
  },
  {
    path: '/404',
    component: () => import(/* webpackChunkName: "404" */ '../views/Error.vue')
  }
]

// component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')

const router = new VueRouter({
  routes
})

// 1.0 根据一个函数，在登录之后，还有页面刷新之后，计算路由
calcRoutes()
export function calcRoutes() {
  const role = local.get('role')
  if (!role) return
  // 只有登录成功了才需要计算
  const finallyRoute = filterRoute(SyncRouter.routes, role)
  // ！！！ 权限设计的核心方法 addRoutes 添加数组   addRoute 添加对象
  routes[0].children = routes[0].children.concat(finallyRoute)
  // router.addRoutes(finallyRoute)*
  router.addRoute(routes[0])

  // 计算菜单  -- routes[0].children
  const menus = filterMenus(routes[0].children)
  // console.log(menus)
  local.set('menus', JSON.stringify(menus))
}

function filterMenus(arr) {
  return arr.filter(item => {
    if (!item.hidden) {
      // 如果有嵌套的路由
      if (item.children) {
        item.children = filterMenus(item.children)
      }
      return true
    } else {
      return false
    }
  })
}

// 2.0 真正干活儿的函数
function filterRoute(arr, role) {
  // 根据定义的字段，过滤出一套数组 - true 就是保留    false  不保留
  return arr.filter(item => {
    if (item.meta && item.meta.role) {
      // 还需要鉴权 includes 是否包含
      if (item.meta.role.includes(role)) {
        if (item.children) {
          item.children = filterRoute(item.children, role)
        }
        return true
      } else {
        return false
      }
    } else {
      // 如果没有role数组，就证明都可以访问的，保留下来
      return true
    }
  })
}

// 路由的钩子 - 导航守卫
router.beforeEach((to, from, next) => {
  const token = local.get('token')
  if (token) {
    next()
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
